package org.jctc.els.modules.biz.controller;

import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.jctc.els.modules.biz.entity.ElsUserProject.ElsUserProject;
import org.jctc.els.modules.biz.entity.elsTeamMembers.ElsTeamMembers;
import org.jctc.els.modules.biz.entity.elsTeamProject.ElsTeamProject;
import org.jctc.els.modules.biz.entity.projects.ElsProjects;
import org.jctc.els.modules.biz.entity.user.User;
import org.jctc.els.modules.biz.service.elsTeamMembers.ElsTeamMembersService;
import org.jctc.els.modules.biz.service.elsTeamProject.ElsTeamProjectService;
import org.jctc.els.modules.biz.service.elsUserProject.ElsUserProjectService;
import org.jctc.els.modules.biz.service.pro.ElsProjectReviewService;
import org.jctc.els.modules.biz.service.projects.ElsProjectsService;
import org.jctc.els.modules.biz.service.team.ITeamService;
import org.jctc.els.modules.biz.service.user.IUserService;
import org.jctc.els.modules.biz.vo.ElsTeamMembersVO;
import org.jctc.els.modules.biz.vo.ElsTeamProjectVO;
import org.jctc.els.modules.biz.vo.ElsUserProjectVO;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.annotation.MultipartConfig;
import java.util.ArrayList;
import java.util.List;

/**
 * @author maxinyu
 * @title: userProjectTeam
 * @projectName evaluationsystem-boot
 * @description:
 * @date 2022/6/219:43
 */


@RestController
@RequestMapping("/userProjectTeam")
@NonDS
@ApiIgnore
@AllArgsConstructor
@MultipartConfig
public class UserProjectTeamController {
    private ElsUserProjectService elsUserProjectService;
    private ElsTeamMembersService elsTeamMembersService;
    private IUserService userService;
    private ElsProjectsService elsProjectsService;
    private ElsTeamProjectService elsTeamProjectService;
    private ITeamService teamService;
    private ElsProjectReviewService elsProjectReviewService;

    //查询专家列表
    @GetMapping("/expertPage")
    public R<IPage<User>> selectExpertListByPage(@ApiIgnore Query query) {
        System.out.println("query" + query);
        IPage<User> expert = userService.selectExpertListByPage(Condition.getPage(query));
        return R.data(expert);
    }

    //新增小组成员
    @ApiOperation(value = "新增小组成员表")
    @PostMapping("/saveElsTeamMembers")
    public R saveElsTeamMembers(@RequestBody ElsTeamMembers elsTeamMembers) {
        elsTeamMembers.setCanLeader(0);//小组绑定专家时，还没有设置组长组员，所以默认为组员
        elsTeamMembers.setRevision(0L);//乐观锁默认设为0
        boolean res = false;
        //判断数据库中此小组是否已存在该成员
        int count = elsTeamMembersService.selectUserAlreadyExists(elsTeamMembers.getUserId(), elsTeamMembers.getTeamId());
        if (count == 0) {
            res = elsTeamMembersService.save(elsTeamMembers);
        }
        return R.status(res);
    }

    //获取这个小组绑定的所有专家
    @GetMapping("/getBoundExpertsList")
    public R<IPage<User>> selectBoundExpertsListByPage(
            @ApiIgnore Query query, @RequestParam(value = "teamId", required = false) String teamId) {
        System.out.println("query" + query);
        IPage<User> boundExperts = userService.selectBoundExpertsListByPage(Condition.getPage(query), teamId);
        return R.data(boundExperts);
    }


    //獲取小組专家表数据 team_member
    @GetMapping("/getExpertsList")
    public R<IPage<ElsTeamMembersVO>> getExpertsList(
            @ApiIgnore Query query, @RequestParam(value = "teamId", required = false) String teamId) {
        System.out.println("query" + query);
        IPage<ElsTeamMembersVO> boundExperts = elsTeamMembersService.getExpertsList(Condition.getPage(query), teamId);
        return R.data(boundExperts);
    }

    //获取小组绑定的所有项目 team_project
    @GetMapping("/getProjectsList")
    public R<IPage<ElsTeamProjectVO>> getProjectsList(
            @ApiIgnore Query query, @RequestParam(value = "teamId", required = false) String teamId) {
        //System.out.println("query"+query);
        IPage<ElsTeamProjectVO> boundProject = elsTeamProjectService.getProjectsList(Condition.getPage(query), teamId);
        return R.data(boundProject);
    }

    //获取某位专家的项目列表 user_project
    @GetMapping("/getUserProjectsList")
    public R<IPage<ElsUserProjectVO>> getUserProjectsList(
            @ApiIgnore Query query,
            @RequestParam(value = "teamId", required = false) String teamId,
            @RequestParam(value = "userId", required = false) String userId) {
        //System.out.println("query"+query);
        IPage<ElsUserProjectVO> boundProject = elsUserProjectService.getProjectsList(Condition.getPage(query), teamId, userId);
        return R.data(boundProject);
    }


    //获取所有项目
    @GetMapping("/getProjectsListByPage")
    public R<IPage<ElsProjects>> selectProjectsListByPage(
            @ApiIgnore Query query,
            @RequestParam(value = "projectNumber") String projectNumber,
            @RequestParam(value = "orgName") String orgName,
            @RequestParam(value = "projectName") String projectName,
            @RequestParam(value = "category1") String category1,
            @RequestParam(value = "category2") String category2,
            @RequestParam(value = "category3") String category3,
            @RequestParam(value = "projectLevel") String projectLevel,
            @RequestParam(value = "trainingCategory") String trainingCategory,
            @RequestParam(value = "trainingType") String trainingType,
            @RequestParam(value = "trainingMode") String trainingMode,
            @RequestParam(value = "deptApply") String deptApply,
            @RequestParam(value = "deptHost") String deptHost,
            @RequestParam(value = "orgBy") String orgBy,
            @RequestParam(value = "implementScope") String implementScope,
            @RequestParam(value = "purchaseCategory") String purchaseCategory,
            @RequestParam(value = "specializedCategory") String specializedCategory,
            @RequestParam(value = "openTime", required = false) String openTime,
            @RequestParam(value = "completionTime", required = false) String completionTime,
            @RequestParam(value = "projectType") Integer projectType
    ) {
        System.out.println("query" + query);
        IPage<ElsProjects> elsProjects = elsProjectsService.selectProjects(Condition.getPage(query),
                projectNumber,
                orgName,
                projectName,
                category1,
                category2,
                category3,
                projectLevel,
                trainingCategory,
                trainingType,
                trainingMode,
                deptApply,
                deptHost,
                orgBy,
                implementScope,
                purchaseCategory,
                specializedCategory,
                openTime,
                completionTime,
                projectType
        );
        return R.data(elsProjects);
    }

    //新增小组项目关联表，项目和小组进行绑定
    @ApiOperation(value = "新增小组项目关联表")
    @PostMapping("/saveElsTeamProject")
    public R saveElsTeamProject(@RequestBody ElsTeamProject elsTeamProject) {
        elsTeamProject.setRevision(0L);//乐观锁默认设为0
        boolean res = false;
        //判断数据库中此小组是否已存在该项目
        int count = elsTeamProjectService.selectProjectAlreadyExists(elsTeamProject.getProjectId(), elsTeamProject.getTeamId());
        if (count == 0) {
            //不存在入库
            res = elsTeamProjectService.save(elsTeamProject);
        }
        return R.status(res);
    }

    //批量新增小组项目关联表，项目和小组进行绑定
    @ApiOperation(value = "新增小组项目关联表")
    @PostMapping("/saveElsTeamProjects")
    @Transactional(rollbackFor = Exception.class)
    public R saveElsTeamProjects(@RequestParam String ids, @RequestParam String teamId) {
        List<ElsTeamProject> list = new ArrayList();
        List<Long> ids1 = Func.toLongList(ids);
        for (Long aLong : ids1) {
            ElsProjects byId = elsProjectsService.getById(aLong);
            if (byId.getProjectReviewId() == 0) {
                throw new ServiceException(byId.getProjectName() + "未绑定维度");
            }
        }
        ids1.forEach((id) -> {
            ElsTeamProject elsTeamProject = new ElsTeamProject();
            elsTeamProject.setProjectId(id);
            elsTeamProject.setTeamId(Long.parseLong(teamId));
            list.add(elsTeamProject);
        });
        boolean res = false;
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            //判断数据库中此小组是否已存在该项目
            count += elsTeamProjectService.selectProjectAlreadyExists(list.get(i).getProjectId(), list.get(i).getTeamId());
        }
        if (count == 0) {
            //不存在就可以入库
            for (int i = 0; i < list.size(); i++) {
                res = elsTeamProjectService.save(list.get(i));
                if (BooleanUtil.isFalse(res)) {
                    throw new ServiceException("绑定项目失败");
                }
            }
        }
        return R.status(res);
    }


    //获取这个小组绑定的所有项目
    @GetMapping("/getBoundProjectsList")
    public R<IPage<ElsProjects>> getBoundProjectsList(
            @ApiIgnore Query query, @RequestParam(value = "teamId", required = false) String teamId,
            @RequestParam(value = "projectNumber") String projectNumber,
            @RequestParam(value = "orgName") String orgName,
            @RequestParam(value = "projectName") String projectName,
            @RequestParam(value = "category1") String category1,
            @RequestParam(value = "category2") String category2,
            @RequestParam(value = "category3") String category3,
            @RequestParam(value = "projectLevel") String projectLevel,
            @RequestParam(value = "trainingCategory") String trainingCategory,
            @RequestParam(value = "trainingType") String trainingType,
            @RequestParam(value = "trainingMode") String trainingMode,
            @RequestParam(value = "deptApply") String deptApply,
            @RequestParam(value = "deptHost") String deptHost,
            @RequestParam(value = "orgBy") String orgBy,
            @RequestParam(value = "implementScope") String implementScope,
            @RequestParam(value = "purchaseCategory") String purchaseCategory,
            @RequestParam(value = "specializedCategory") String specializedCategory,
            @RequestParam(value = "openTime", required = false) String openTime,
            @RequestParam(value = "completionTime", required = false) String completionTime) {
        System.out.println("query" + query);
        IPage<ElsProjects> elsProjects = elsProjectsService.selectBoundProjects(Condition.getPage(query), teamId, projectNumber,
                orgName,
                projectName,
                category1,
                category2,
                category3,
                projectLevel,
                trainingCategory,
                trainingType,
                trainingMode,
                deptApply,
                deptHost,
                orgBy,
                implementScope,
                purchaseCategory,
                specializedCategory,
                openTime,
                completionTime);
        return R.data(elsProjects);
    }


    @ApiOperation(value = "新增用户项目关联表")
    @PostMapping("/saveElsUserProject")
    @Transactional(rollbackFor = Exception.class)
    public R saveElsUserProject(@RequestParam String expertsIds, @RequestParam String projectsIds, @RequestParam String teamId) {
        //------------------->>>小组绑定专家
        List<ElsTeamMembers> listExperts = new ArrayList();
        List<Long> idsExperts = Func.toLongList(expertsIds);//专家id
        idsExperts.forEach((id) -> {
            ElsTeamMembers elsTeamMembers = new ElsTeamMembers();
            elsTeamMembers.setUserId(id);
            elsTeamMembers.setTeamId(Long.parseLong(teamId));//项目id
            elsTeamMembers.setCanLeader(0);//小组绑定专家时，还没有设置组长组员，所以默认为组员
            elsTeamMembers.setRevision(0L);//乐观锁默认设为0
            elsTeamMembers.setStatus(0);
            elsTeamMembers.setIsDeleted(0);
            listExperts.add(elsTeamMembers);
        });

        boolean res = false;
        int countExperts = 0;
        for (int i = 0; i < listExperts.size(); i++) {
            //判断数据库中此小组是否已存在该成员
            countExperts += elsTeamMembersService.selectUserAlreadyExists(listExperts.get(i).getUserId(), listExperts.get(i).getTeamId());
        }
        if (countExperts == 0) {
            //不存在就可以入库
            for (int i = 0; i < listExperts.size(); i++) {
                res = elsTeamMembersService.save(listExperts.get(i));
                if (BooleanUtil.isFalse(res)) {
                    throw new ServiceException("绑定专家失败");
                }
            }
        }
        //------------------->>>小组绑定项目
        List<ElsTeamProject> listProject = new ArrayList();
        List<Long> idsProject = Func.toLongList(projectsIds);
        for (Long aLong : idsProject) {
            ElsProjects byId = elsProjectsService.getById(aLong);
            if (byId.getProjectReviewId() == 0) {
                throw new ServiceException(byId.getProjectName() + "未绑定维度");
            }
        }
        idsProject.forEach((id) -> {
            ElsTeamProject elsTeamProject = new ElsTeamProject();
            elsTeamProject.setProjectId(id);
            elsTeamProject.setTeamId(Long.parseLong(teamId));
            listProject.add(elsTeamProject);
        });
        int countProject = 0;
        for (int i = 0; i < listProject.size(); i++) {
            //判断数据库中此小组是否已存在该项目
            countProject += elsTeamProjectService.selectProjectAlreadyExists(listProject.get(i).getProjectId(), listProject.get(i).getTeamId());
        }
        if (countProject == 0) {
            //不存在就可以入库
            for (int i = 0; i < listProject.size(); i++) {
                res = elsTeamProjectService.save(listProject.get(i));
                if (BooleanUtil.isFalse(res)) {
                    throw new ServiceException("绑定项目失败");
                }
            }
        }
        //------------------->>>专家绑定项目
        List<ElsUserProject> list = new ArrayList();
        List<Long> ids1 = Func.toLongList(expertsIds);//专家id
        List<Long> ids2 = Func.toLongList(projectsIds);//项目id
        ids1.forEach((idExperts) -> {
            System.out.println("专家id--》》》》" + idExperts);
            ids2.forEach((idProjects) -> {
                ElsUserProject elsUserProject = new ElsUserProject();
                elsUserProject.setUserId(idExperts);
                elsUserProject.setProjectId(idProjects);//项目id
                System.out.println("项目id--》》》》" + idExperts);
                list.add(elsUserProject);
            });
        });
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            //查询专家是否已绑定项目
            count += elsUserProjectService.selectUserProjectAlreadyExists(list.get(i).getUserId(), list.get(i).getProjectId());

        }
        if (count == 0) {
            for (int i = 0; i < list.size(); i++) {
                res = elsUserProjectService.save(list.get(i));
                if (BooleanUtil.isFalse(res)) {
                    throw new ServiceException("专家绑定项目失败");
                }
            }
        } else {
            throw new ServiceException("专家绑定项目重复,请重新选择绑定");
        }

        return R.status(res);
    }

    //批量新增小组成员
    @ApiOperation(value = "批量新增小组成员表")
    @PostMapping("/saveUsers")
    @Transactional(rollbackFor = Exception.class)
    public R saveUsers(@RequestParam String userIds, @RequestParam String teamId) {
        //------------------->>>小组绑定专家
        List<ElsTeamMembers> listExperts = new ArrayList();
        List<Long> idsExperts = Func.toLongList(userIds);//专家id
        idsExperts.forEach((id) -> {
            ElsTeamMembers elsTeamMembers = new ElsTeamMembers();
            elsTeamMembers.setUserId(id);
            elsTeamMembers.setTeamId(Long.parseLong(teamId));//项目id
            elsTeamMembers.setCanLeader(0);//小组绑定专家时，还没有设置组长组员，所以默认为组员
            elsTeamMembers.setRevision(0L);//乐观锁默认设为0
            elsTeamMembers.setStatus(0);
            elsTeamMembers.setIsDeleted(0);
            listExperts.add(elsTeamMembers);
        });

        boolean res = false;
        int countExperts = 0;
        for (int i = 0; i < listExperts.size(); i++) {
            //判断数据库中此小组是否已存在该成员
            countExperts += elsTeamMembersService.selectUserAlreadyExists(listExperts.get(i).getUserId(), listExperts.get(i).getTeamId());
        }
        if (countExperts == 0) {
            //不存在就可以入库
            for (int i = 0; i < listExperts.size(); i++) {
                res = elsTeamMembersService.save(listExperts.get(i));
                if (BooleanUtil.isFalse(res)) {
                    throw new ServiceException("绑定专家失败");
                }
            }
        }
        return R.status(res);
    }

    /**
     * 解绑专家
     *
     * @param teamId
     * @param userIds
     */
    @DeleteMapping("/deleteTeamExperts")
    public R deleteTeamExperts(Long teamId, String userIds) {
        //专家ID
        List<Long> userIdList = Func.toLongList(userIds);
        boolean result = elsTeamMembersService.removeTeamMembers(teamId, userIdList);
        return R.status(result);
    }

    //解绑项目
    @DeleteMapping("/deleteTeamProject")
    public void deleteTeamProject(String ids) {
        //删除项目表里的数据
        elsTeamProjectService.removeListByIds(Func.toLongList(ids));
    }

    //解绑专家项目 user_project
    @DeleteMapping("/deleteUserProject")
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        System.out.println(ids);
        List<Long> longs = Func.toLongList(ids);
        if (longs.size() > 0) {
            for (Long aLong : longs) {
                ElsUserProject elsUserProject = elsUserProjectService.selectUserProject(aLong);
                Integer integer = elsProjectReviewService.selectByid(elsUserProject.getProjectId());
                if (integer > 0) {
//                return R.status(false);
                    throw new ServiceException("项目已打分不可解绑!");
                }
            }
        } else {
            throw new ServiceException("请选中至少一行!");
        }

        return R.status(elsUserProjectService.deleteLogic(Func.toLongList(ids)));
    }

    //设置组长
    @ApiOperation(value = "设置组长，修改team_member表")
    @PutMapping("/updateExpertsLeader")
    public R updateExpertsLeader(String id, String teamId) {
        boolean b = false;
        //查询该小组是否有组长
        ElsTeamMembers result = elsTeamMembersService.selectUserLeader(teamId);
        if (result != null) {
            elsTeamMembersService.updateLeader(result.getId().toString(), 0);
        }
        b = elsTeamMembersService.updateLeader(id, 1);

        //1.查询小组长的id --- result1.getUserId()
        //2.设置team表中的team_leader （存放组长的id）
        ElsTeamMembers result1 = elsTeamMembersService.selectUserLeader(teamId);
        teamService.updateTeamLeader(result1.getUserId(), teamId);

        return R.data(b);
    }

    /**
     * 解绑项目
     *
     * @param teamId
     * @param projectIds
     */
    @DeleteMapping("/deleteTeamProjects")
    public R deleteTeamProjects(Long teamId, String projectIds) {
        //项目ID
        List<Long> projectIdList = Func.toLongList(projectIds);
        for (Long aLong : projectIdList) {
            Integer integer = elsProjectReviewService.selectByid(aLong);
            if (integer > 0) {
                throw new ServiceException("项目已打分不可解绑!");
            }
        }
        boolean result = elsTeamProjectService.removeTeamProjects(teamId, projectIdList);
        return R.status(result);
    }
}
